package com.item.action;

import com.base.action.CoreController;
import com.base.dao.model.Ret;
import com.base.des.Md5;
import com.base.dialect.PaginationSupport;
import com.base.web.annotation.LoginFilter;
import com.item.dao.model.User;
import com.item.dao.model.UserExample;
import com.item.daoEx.model.UserEx;
import com.item.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("user")
@Controller
@LoginFilter
public class UserController extends CoreController{
	@Autowired
	private UserService userService;

	@RequestMapping("list")
	@ResponseBody
	public String selectUserList(String name,Integer page,Integer rows) throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("key", name);
		PaginationSupport.byPage(page, rows);
		List<UserEx> list= userService.selectList(map);
		return page(list);
	}
	
	@RequestMapping("/findById")
	@ResponseBody
	public String findById(Integer id){
		User user = userService.selectByPrimaryKey(id);
		return ok(user);
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public String update(User user){
		if(!StringUtils.isBlank(user.getPassword()))
		    user.setPassword(Md5.mD5(user.getPassword()));
		this.userService.updateByPrimaryKeySelective(user);
		return ok();
	}
	
	@RequestMapping("/isExist")
	@ResponseBody
	public String isExist(String value){
		Ret ret = new Ret(0);
		User user = userService.selectByPrimaryKey(Integer.parseInt(value));
		if (user == null) {
			ret.setCode(1);
		}
		return ok(ret);
	}
	
	@RequestMapping("/save")
	@ResponseBody
	public String save(User user){
//		String pwd = ToolsUtil.getRandomString(8);
		if (user.getId() == null) {
			user.setPassword(Md5.mD5("666666"));
//			user.setBalance(BigDecimal.ZERO);
//			user.setCredit(0);
			user.setState(1);
			user.setCreateTime(new Date());
			user.setIsComplete(0);
			userService.insert(user);
//			userCouponService.regist(user.getId());
		} else {
			userService.updateByPrimaryKeySelective(user);
		}
		
		return ok();
	}
	
	@RequestMapping("/isAccountExist")
	@ResponseBody
	public String isAccountExist(String value){
		Ret ret = new Ret(0);
		UserExample example = new UserExample();
		example.createCriteria().andAccountEqualTo(value);
		int cnt = userService.countByExample(example);
		if (cnt > 0) {
			ret.setCode(1);
		}
		return ok(ret);
	}
	
}
